var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();
var reload = true;
var page = 1;
var hasMore = true;
var loadingMore = false;

var SDKVersion = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopData: '',

    uid: 0,
    token: '',
    openid: '',

    colorSet: '',

    shopIds: '',
  },

  isSelShop: false,
  yhqId: '',
  

  searchVal: "",

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    })

    wx.setNavigationBarTitle({
      title: '选择门店'
    })

    this.yhqId = options.id ? options.id : '';
    var shopIds = options.shopids ? options.shopids : '';
    this.isSelShop = options.selshop == 'true';

    page = 1;
    hasMore = true;
    loadingMore = false;

    var that = this;

    wx.getSystemInfo({
      success: function(res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          yhq_img_w: res.windowWidth,
          shopIds: shopIds
        });
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function(res) {
      var authFail = res == -1; //用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }
    });

    if(shopIds){
      //读取指定的适用门店
      this.loadUserByIds(shopIds);
    } else {
      //读取经销商/门店 列表
      this.loadUserByCata(1);
    }
  },

  //读取指定的适用门店
  loadUserByIds: function (userIds) {
    // http://api.maxdoge.com/api.php?publickey=ZGZvI1mi8Q&ac=getmendianids&shopids=11755,1,11603
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getmendianids",
      shopids: userIds
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("门店数据：", result);
        that.setData({
          shopData: result
        });
        wx.hideLoading();
      }
    });
  },

  inputVal: function (e) {
    this.searchVal = e.detail.value
  },
  search: function () {
    page = 1;
    this.selIndex = -1;
    this.loadUserByCata(page);
  },

  selIndex: -1,
  selectAction:function(e){
    var index = e.currentTarget.dataset.index;
    if(this.selIndex != index){
      var allShopData = this.data.shopData;
      if(this.selIndex != -1){
        allShopData[this.selIndex].sel = false;
      }
      allShopData[index].sel = true;
      this.setData({
        shopData: allShopData
      })
    }
    this.selIndex = index;
  },

  loadMore: function(e) {
    if(this.data.shopIds){
      //有指定使用门店的，不用分页加载
      return;
    }
    if (hasMore && !loadingMore) {
      loadingMore = true;
      page++;
      this.loadUserByCata(page);
    } else {
      console.log("没有更多了");
    }
  },

  // 读取门店类型的用户
  loadUserByCata: function(cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getcatauser",
      orgid: util.orgid,
      usercata: '20',
      shopuid: '',
      page: cpage,
      num: 10
    }
    if (this.searchVal && this.searchVal.length > 0){
      params = {
        publickey: util.publiccode,
        ac: "searchcatauser",
        keyword: this.searchVal,
        catatype: '20',
        page: cpage,
        num: 10
      };
    }
    util.api({
      data: params,
      success: function(responseData) {
        var result = responseData.data;
        console.log("门店数据：", result);
        if (!result.msg) {
          // result.forEach(function (m, i) {
          //   if (m.photos) {
          //     result[i].photosData = m.photos.split(",");
          //   }
          //   result[i].message = app.parseHTMLText(m.message);
          // });

          if (cpage <= 1) {
            that.setData({
              shopData: result
            });
          } else {
            that.setData({
              shopData: that.data.shopData.concat(result)
            });
          }
        } else {
          if (cpage <= 1) {
            that.setData({
              shopData: []
            });
          }
          hasMore = false;
        }
        loadingMore = false;

        if (that.data.shopData.length <= 0) {
          that.setData({
            hasData: false
          })
        } else {
          that.setData({
            hasData: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function() {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },
  goAtherPageRedirect: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({
      url: url
    })
  },

  //保存formId
  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({
          url: path
        });
      }
    }
  },

  makeCallPhone: function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  useYouHuiQuan: function (e) {
    
    console.log("formid: ", e.detail.formId);
    app.saveFormId(e.detail.formId);//保存fromId
    if(this.selIndex == -1){
      var title = (util.orgid == '25354' ? '请选择一个门诊' : '请选择一个门店');
      wx.showToast({
        icon: "none",
        title: title,
      })
      return;
    }

    var that = this;
    if (this.isSelShop){//核销员认证 选择门店
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1];  //当前页面
      var prevPage = pages[pages.length - 2]; //上一个页面
      var shopInfo = this.data.shopData[this.selIndex];
      //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
      prevPage.setSelectShop(shopInfo);
      wx.navigateBack({
        delta: 1
      });
    } else {
      var shopId = that.data.shopData[that.selIndex].uid;
      var shareImgUrl = util.api_host + "/wxxcxcode.php?quan=1&quanid=" + this.yhqId + "&shopid=" + shopId + "&binduid=" + util.orgid;
      shareImgUrl = base64.encode(shareImgUrl);
      var url = "/pages/haibao-page/haibao-page?yhq=true&title=优惠券核销&imgUrl=" + shareImgUrl;
      //测试代码，发布时一定要注释掉
      // var url = "/pages/hexiao/hexiao?quanid=" + this.yhqId + "&shopid=" + shopId;
      wx.navigateTo({ url: url });
    }
    
  },

})